package zxj.weixin.mp.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import zxj.weixin.mp.domain.Account;
import zxj.weixin.mp.mapper.AccountMapper;
import zxj.weixin.utils.RedisUtils;

/**
 * 微信公众号Service
 * 
 * @author zhuxuejiang
 *
 */
@Service
public class AccountService {

	private static final String KEY_OFFICIAL_ACCOUNT = "wx_official_account.";
	private static final long TIMEOUT_OFFICIAL_ACCOUNT = 60;

	@Autowired
	private RedisUtils<String, Account> redisUtils;

	@Autowired
	private AccountMapper accountMapper;

	/**
	 * 查询微信公众号
	 * 
	 * @param appId 公众号的唯一标识
	 * @return 微信公众号DO
	 */
	public Account getByAppId(String appId) {

		String key = KEY_OFFICIAL_ACCOUNT + appId;

		if (redisUtils.hasKey(key)) {
			return (Account) redisUtils.opsForValueGet(key);
		}

		Account account = accountMapper.selectByPrimaryKey(appId);
		redisUtils.opsForValueSet(key, account, TIMEOUT_OFFICIAL_ACCOUNT);

		return account;
	}

	/**
	 * 查询微信公众号
	 * 
	 * @param wxId 微信原始ID
	 * @return 微信公众号DO
	 */
	public Account getByWxId(String wxId) {

		String key = KEY_OFFICIAL_ACCOUNT + wxId;

		if (redisUtils.hasKey(key)) {
			return (Account) redisUtils.opsForValueGet(key);
		}

		Account account = accountMapper.selectByWxId(wxId);
		redisUtils.opsForValueSet(key, account, TIMEOUT_OFFICIAL_ACCOUNT);

		return account;
	}

}
